from flask import Flask
from flask_cors import CORS
from .config import Config
from .routes.api import bp
from .models import db
from flask import Flask
import os
from flask_jwt_extended import JWTManager
# from .config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from datetime import timedelta
# db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    app = Flask(__name__)

    # 必须配置 JWT 密钥（生产环境要用更安全的密钥）
    app.config['JWT_SECRET_KEY'] = 'your-super-secret-key'  # 改成你的密钥
    app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)  # 可选：设置过期时间
    app.config['SQLALCHEMY_DATABASE_URI'] ='sqlite:///database.db'
    app.config['VECTOR_DB_PATH']='data/vector_db'
    app.config['DOCUMENT_STORE']='data/documents'
    # VECTOR_DB_PATH = 'data/vector_db'           # 向量数据库路径
    # DOCUMENT_STORE = 'data/documents'           # 文档存储路径
    # 初始化JWT
    jwt = JWTManager(app)

    #如果文件夹不存在，则新建    VECTOR_DB_PATH DOCUMENT_STORE
    if not os.path.exists(Config.VECTOR_DB_PATH):
        os.makedirs(Config.VECTOR_DB_PATH)
    if not os.path.exists(Config.DOCUMENT_STORE):
        os.makedirs(Config.DOCUMENT_STORE)

    # 启用CORS
    CORS(app)

    # 初始化数据库
    db.init_app(app)
    # db.init_app(app)
    migrate.init_app(app, db)  # 关键初始化

    # 注册蓝图

    app.register_blueprint(bp)

    return app